﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using MySql.Data.MySqlClient;

namespace TKWeb
{
	public partial class ObjCatManage : System.Web.UI.Page
	{
		private DataTable objCats;
		private DataTable ObjCats
		{
			get
			{
				if (objCats == null)
				{
					objCats = Global.DBAccess.GetTable("select * from obj_cat");
				}
				return objCats;
			}
		}

		protected void Page_Load(object sender, EventArgs e)
		{
			if (!this.IsPostBack)
			{
				this.BindTreeView();
			}
		}

		private void BindTreeView()
		{
			BindTreeNode(tvCat.Nodes, 0);
		}

		private void BindTreeNode(TreeNodeCollection nodes, int parentCId)
		{
			DataRow[] rows = this.ObjCats.Select("parent_cid='" + parentCId + "'");
			if (rows != null && rows.Length > 0)
			{
				TreeNode node = null;
				foreach (DataRow dr in rows)
				{
					bool exist = false;
					int cid = Convert.ToInt32(dr["cid"]);
					foreach (TreeNode n in nodes)
					{
						if (n.Value == cid.ToString())
						{
							node = n;
							exist = true;
							break;
						}
					}

					if (!exist)
					{
						node = new TreeNode(dr["Name"].ToString(), cid.ToString());
						node.Expanded = (node == tvCat.SelectedNode);
						nodes.Add(node);
					}
					BindTreeNode(node.ChildNodes, cid);
				}
			}
		}

		private static string[] s_DataTypeString = new string[]{"词", "文本", "库"};
		protected string GetDataTypeString(object type)
		{
			int index = Convert.ToInt32(type) - 1;
			return s_DataTypeString[index];
		}

		private void BindPropList(int cid)
		{
			gvProp.DataSource = Global.DBAccess.GetTable("select t.*,(select name from obj_prop where t.pid = pid) pname from obj_cat_prop t where t.cid=" + cid);
			gvProp.DataBind();
		}

		private void ShopPropAddPanel()
		{
			divAddProp.Visible = true;
			divProp.Visible = false;
			divFieldMapSet.Visible = false;
			this.BindPropEdit(this.CatPID);
		}

		private void ShopPropListPanel()
		{
			divAddProp.Visible = false;
			divFieldMapSet.Visible = false;
			divProp.Visible = true;
			if (tvCat.SelectedNode != null)
			{
				this.BindPropList(Convert.ToInt32(tvCat.SelectedNode.Value));
			}
		}

		private void ShopFieldMapPanel()
		{
			divAddProp.Visible = false;
			divProp.Visible = false;
			divFieldMapSet.Visible = true;
			ddlCrawlJob.Items.Clear();
			ddlCrawlFile.Items.Clear();
			this.BindCrawlJob();
		}

		protected void tvCat_SelectedNodeChanged(object sender, EventArgs e)
		{
			this.ShopPropListPanel();
		}

		protected void tvCat_TreeNodeCollapsed(object sender, TreeNodeEventArgs e)
		{
			BindTreeView();
		}

		protected void btnAdd_Click(object sender, EventArgs e)
		{
			string name = tbName.Text.Trim();
			if (string.IsNullOrEmpty(name))
			{
				return;
			}

			int parentCId = 0;
			if(tvCat.SelectedNode != null)
			{
				parentCId = Convert.ToInt32(tvCat.SelectedNode.Value);
			}

			Global.DBAccess.ExecuteNonQuery("insert into obj_cat(name,parent_cid) values(@name,@parent_cid)",
				new MySqlParameter("name", name),
				new MySqlParameter("parent_cid", parentCId)
			);

			if (parentCId > 0)
			{
				Global.DBAccess.ExecuteNonQuery("update obj_cat set IS_PARENT=1 where cid=@cid",
					new MySqlParameter("cid", parentCId)
				);
			}

			tbName.Text = "";
			this.BindTreeView();
		}

		protected void btnRefresh_Click(object sender, EventArgs e)
		{
			Response.Redirect("/ObjCatManage.aspx");
		}

		protected void lbAddProp_Click(object sender, EventArgs e)
		{
			this.CatPID = 0;
			tbPropName.Text = "";
			tbDataSize.Text = "0";
			tbSortOrder.Text = "0";
			ddlDataType.SelectedValue = "1";
			ddlMust.SelectedValue = "1";
			ddlPropEnum.SelectedValue = "0";
			ddlPropInput.SelectedValue = "0";
			ddlPropKey.SelectedValue = "0";
			ddlPropStatus.SelectedValue = "1";
			this.ShopPropAddPanel();
		}

		private int GetPropIdByName(string name)
		{
			object objPId = Global.DBAccess.ExecuteScalar("select pid from obj_prop where name=@name", new MySqlParameter("name", name));
			if (objPId != null)
			{
				return Convert.ToInt32(objPId);
			}

			return (int)Global.DBAccess.InsertData("insert into obj_prop(name) values(@name)", new MySqlParameter[]{ new MySqlParameter("name", name) });
		}

		protected void btnOK_Click(object sender, EventArgs e)
		{
			string propName = tbPropName.Text.Trim();
			if (string.IsNullOrEmpty(propName))
			{
				return;
			}

			int cid = Convert.ToInt32(tvCat.SelectedNode.Value);
			int pid = GetPropIdByName(propName);
			int dataSize = 0;
			int sortOrder = 0;
			int.TryParse(tbDataSize.Text.Trim(), out dataSize);
			int.TryParse(tbSortOrder.Text.Trim(), out sortOrder);
			MySqlParameter[] pars = new MySqlParameter[]{
				new MySqlParameter("pid",pid),
				new MySqlParameter("cid",cid),
				new MySqlParameter("data_type",ddlDataType.SelectedValue),
				new MySqlParameter("data_size",dataSize),
				new MySqlParameter("is_key_prop",ddlPropKey.SelectedValue),
				new MySqlParameter("is_enum_prop",ddlPropEnum.SelectedValue),
				new MySqlParameter("is_input_prop",ddlPropInput.SelectedValue),
				new MySqlParameter("must",ddlMust.SelectedValue),
				new MySqlParameter("sort_order",sortOrder),
				new MySqlParameter("status",ddlPropStatus.SelectedValue),
				new MySqlParameter("cat_pid",this.CatPID)
			};
			if (this.CatPID > 0)
			{
				Global.DBAccess.ExecuteNonQuery(@"update obj_cat_prop set 
					pid=@pid,
					data_type=@data_type,
					data_size=@data_size,
					is_key_prop=@is_key_prop,
					is_enum_prop=@is_enum_prop,
					is_input_prop=@is_input_prop,
					must=@must,
					status=@status,
					sort_order=@sort_order where cat_pid=@cat_pid", pars);
			}
			else
			{
				Global.DBAccess.ExecuteNonQuery(@"insert into obj_cat_prop(pid,cid,data_type,data_size,is_key_prop,is_enum_prop,is_input_prop,must,sort_order) values(@pid,@cid,@data_type,@data_size,@is_key_prop,@is_enum_prop,@is_input_prop,@must,@sort_order)", pars);
			}
			this.CatPID = 0;
			this.ShopPropListPanel();
		}

		protected void gvProp_RowCommand(object sender, GridViewCommandEventArgs e)
		{
			this.CatPID = Convert.ToInt32(e.CommandArgument);
			switch (e.CommandName)
			{
				case "PropEdit":
					this.ShopPropAddPanel();
					break;

				case "FieldMap":
					this.ShopFieldMapPanel();
					break;
			}
		}

		private int CatPID
		{
			get
			{
				if (this.ViewState["CatPID"] == null)
				{
					return 0;
				}

				return Convert.ToInt32(this.ViewState["CatPID"]);
			}

			set
			{
				this.ViewState["CatPID"] = value;
			}
		}

		private void BindPropEdit(int catPId)
		{
			this.CatPID = catPId;
			DataTable dt = Global.DBAccess.GetTable("select t.*,(select name from obj_prop where t.pid = pid) pname from obj_cat_prop t where cat_pid=" + catPId);
			if (dt.Rows.Count > 0)
			{
				DataRow dr = dt.Rows[0];
				tbPropName.Text = dr["pname"].ToString();
				tbDataSize.Text = dr["data_size"].ToString();
				tbSortOrder.Text = dr["sort_order"].ToString();
				ddlDataType.SelectedValue = dr["data_type"].ToString();
				ddlMust.SelectedValue = dr["must"].ToString();
				ddlPropEnum.SelectedValue = dr["is_enum_prop"].ToString();
				ddlPropInput.SelectedValue = dr["is_input_prop"].ToString();
				ddlPropKey.SelectedValue = dr["is_key_prop"].ToString();
				ddlPropStatus.SelectedValue = dr["status"].ToString();
			}
		}

		protected void btnBack_Click(object sender, EventArgs e)
		{
			this.ShopPropListPanel();
		}

		protected void btnSetField_Click(object sender, EventArgs e)
		{
			/*
			if (ddlCrawlField.SelectedValue != "0")
			{
				Global.DBAccess.ExecuteNonQuery("delete from crawl_file_field_map where cat_pid=" + CatPID);
				string propTitle = Global.DBAccess.ExecuteScalar("SELECT CONCAT((SELECT  NAME FROM obj_prop WHERE pid=t.pid),'-',(SELECT  NAME FROM obj_cat WHERE cid=t.cid)) FROM obj_cat_prop t WHERE cat_pid="+CatPID).ToString();
				Global.DBAccess.ExecuteNonQuery("insert into crawl_file_field_map(field_id,cat_pid,field_title,cat_prop_title) values(@field_id,@cat_pid,@field_title,@cat_prop_title)", 
					new MySqlParameter("field_id", ddlCrawlField.SelectedValue),
					new MySqlParameter("cat_pid", this.CatPID),
					new MySqlParameter("field_title", ddlCrawlJob.SelectedItem.Text + "-" + ddlCrawlFile.SelectedItem.Text + "-" + ddlCrawlField.SelectedItem.Text),
					new MySqlParameter("cat_prop_title", propTitle)
				);
			}
			 * */
			this.ShopPropListPanel();
		}

		protected void ddlCrawlJob_SelectedIndexChanged(object sender, EventArgs e)
		{
			this.BindCrawlFile(Convert.ToInt32(ddlCrawlJob.SelectedValue));
		}

		private DataTable dtMapData = null;
		protected void ddlCrawlFile_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (!string.IsNullOrEmpty(tvCat.SelectedValue) && !string.IsNullOrEmpty(ddlCrawlFile.SelectedValue) && ddlCrawlFile.SelectedValue != "0")
			{
				dtMapData = Global.DBAccess.GetTable(string.Format("select cat_pid,field_id from crawl_file_field_map t where cid= {0} and file_id={1}", tvCat.SelectedValue, ddlCrawlFile.SelectedValue));
				gvPropMap.DataSource = Global.DBAccess.GetTable("select t.*,(select name from obj_prop where t.pid = pid) pname from obj_cat_prop t where cid=" + tvCat.SelectedValue);
				gvPropMap.DataBind();
			}
		}

		private void BindCrawlJob()
		{
			ddlCrawlJob.Items.Clear();
			ddlCrawlJob.DataSource = Global.DBAccess.GetTable("select * from crawl_job");
			ddlCrawlJob.DataTextField = "name";
			ddlCrawlJob.DataValueField = "job_id";
			ddlCrawlJob.DataBind();
			ddlCrawlJob.Items.Insert(0, new ListItem("选择采集项目", "0"));
		}

		private void BindCrawlFile(int jobId)
		{
			ddlCrawlFile.Items.Clear();
			ddlCrawlFile.DataSource = Global.DBAccess.GetTable("select * from crawl_job_file where job_id="+jobId);
			ddlCrawlFile.DataTextField = "name";
			ddlCrawlFile.DataValueField = "file_id";
			ddlCrawlFile.DataBind();
			ddlCrawlFile.Items.Insert(0, new ListItem("选择采集页面", "0"));
		}

		private void BindCrawlField(int fileId)
		{
			
		}

		protected void btnReturnPropList_Click(object sender, EventArgs e)
		{
			this.ShopPropListPanel();
		}

		protected void btnMapOK_Click(object sender, EventArgs e)
		{
			DropDownList ddlField = null;
			HiddenField hfCatPId = null;
			MySqlTransaction tran = null;
			try
			{
				tran = Global.DBAccess.BeginTransaction();
				Global.DBAccess.ExecuteNonQuery(tran.Connection, "delete from crawl_file_field_map where file_id=@file_id", new MySqlParameter("file_id", ddlCrawlFile.SelectedValue));
				foreach (GridViewRow row in gvPropMap.Rows)
				{
					ddlField = (DropDownList)row.FindControl("ddlField");
					hfCatPId = (HiddenField)row.FindControl("hfCatPId");
					if (!string.IsNullOrEmpty(ddlField.SelectedValue) && ddlField.SelectedValue != "0" && ddlCrawlFile.SelectedValue != "0")
					{
						Global.DBAccess.ExecuteNonQuery(tran.Connection, "insert into crawl_file_field_map(field_id,cat_pid,file_id,cid) values(@field_id,@cat_pid,@file_id,@cid)",
							new MySqlParameter("field_id", ddlField.SelectedValue),
							new MySqlParameter("cat_pid", hfCatPId.Value),
							new MySqlParameter("cid", tvCat.SelectedValue),
							new MySqlParameter("file_id", ddlCrawlFile.SelectedValue)
						);
					}
				}
				tran.Commit();
			}
			catch
			{
				if (tran != null)
				{
					tran.Rollback();
				}
			}
			finally
			{
				if (tran != null)
				{
					tran.Connection.Close();
				}
			}
			this.ShopPropListPanel();
		}

		protected void gvPropMap_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			DataRow[] rows = null;
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				DropDownList ddlField = (DropDownList)e.Row.FindControl("ddlField");
				HiddenField hfCatPId = (HiddenField)e.Row.FindControl("hfCatPId");
				ddlField.DataSource = Global.DBAccess.GetTable("select field_id,name from crawl_file_field where file_id=@file_id", new MySqlParameter[] { new MySqlParameter("file_id", ddlCrawlFile.SelectedValue) });
				ddlField.DataTextField = "name";
				ddlField.DataValueField = "field_id";
				ddlField.DataBind();
				ddlField.Items.Insert(0, new ListItem("请选择字段", "0"));

				rows = dtMapData.Select(" cat_pid=" + hfCatPId.Value);
				if (rows != null && rows.Length > 0)
				{
					ddlField.SelectedValue = rows[0]["field_id"].ToString();
				}
			}
		}

		protected void lbShowPropMap_Click(object sender, EventArgs e)
		{
			gvPropMap.DataSource = null;
			gvPropMap.DataBind();
			this.ShopFieldMapPanel();
		}

		protected void gvPropMap_RowCreated(object sender, GridViewRowEventArgs e)
		{
			
		}
	}
}